package spring.boot.server.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import spring.boot.server.common.NettyServerConstant;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.net.InetSocketAddress;

@Slf4j
@Component
public class NettyServer {

    @Autowired
    private NettyServerHandlerInitializer nettyServerHandlerInitializer;

    /**
     * 启动 Netty Server
     */
    @PostConstruct
    public void start() throws InterruptedException {
        // 创建 ServerBootstrap 对象，用于 Netty Server 启动
        ServerBootstrap bootstrap = new ServerBootstrap();
        // 设置 ServerBootstrap 的各种属性
        bootstrap.group(NettyServerConstant.BOSS_GROUP, NettyServerConstant.WORKER_GROUP) // 设置两个 EventLoopGroup 对象
                .channel(NioServerSocketChannel.class)  // 指定 Channel 为服务端 NioServerSocketChannel
                .localAddress(new InetSocketAddress(NettyServerConstant.SERVER_PORT)) // 设置 Netty Server 的端口
                .option(ChannelOption.SO_BACKLOG, 1024) // 服务端 accept 队列的大小
                .childOption(ChannelOption.SO_KEEPALIVE, true) // TCP Keepalive 机制，实现 TCP 层级的心跳保活功能
                .childOption(ChannelOption.TCP_NODELAY, true) // 允许较小的数据包的发送，降低延迟
                .childHandler(nettyServerHandlerInitializer);
        // 绑定端口，并同步等待成功，即启动服务端
        ChannelFuture future = bootstrap.bind().sync();
        if (future.isSuccess()) {
            NettyServerConstant.CHANNEL = future.channel();
            log.info("Netty服务端启动在端口=[{}]", NettyServerConstant.SERVER_PORT);
        }
    }

    /**
     * 关闭 Netty Server
     * 优雅关闭两个 EventLoopGroup 对象
     */
    @PreDestroy
    public void shutdown() {
        if (NettyServerConstant.CHANNEL != null) {
            NettyServerConstant.CHANNEL.close();
        }
        NettyServerConstant.BOSS_GROUP.shutdownGracefully();
        NettyServerConstant.WORKER_GROUP.shutdownGracefully();
    }

}
